#!/bin/bash
set -e

useage() {
    cat <<HELP
Usage: bump-k3os-version new_k3os_version

  new_k3os_version Specify the K3OS version to update
HELP
}

if [ $# -lt 1 ]; then
    useage
    exit 1
fi

NEW_K3OS_VERSION=$1

k3os_version_file=$(dirname $0)/k3os-version
echo "=> Read K3OS version from file: ${k3os_version_file}"
source ${k3os_version_file}

echo "=> Current K3OS version is ${VERSION}"
if [ "${NEW_K3OS_VERSION}" == "${VERSION}" ]; then
  exit 0
fi

if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
    echo "Check Error: git status dirty"
    exit 1
fi

echo "=> Bump K3OS version to ${NEW_K3OS_VERSION}"

echo "=> Get changes in the K3OS directory since the last version update"
last_k3os_base_commit=$(git log --grep "K3OS base" --pretty=format:"%h"|head -n 1)
k3os_commits=$(git rev-list --reverse ${last_k3os_base_commit}..HEAD -- k3os)

echo "=> Prepare the base commit with the upstream K3OS"
rm -r k3os
git clone --branch ${NEW_K3OS_VERSION} --single-branch --depth 1 https://github.com/rancher/k3os
rm -rf k3os/.git
git add k3os
git commit -m "K3OS base: Bump to ${NEW_K3OS_VERSION}"

echo "=> Pick all changes on the installer side"
git cherry-pick $(echo ${k3os_commits})

echo "=> Update K3OS base version file"
cat > ${k3os_version_file} <<EOF
#!/bin/bash
# Generated by bump-k3os-version. DO NOT EDIT.
VERSION=$NEW_K3OS_VERSION
EOF

cat <<EOF
Next:
   * Resolve conflicts if there's any
   * Build, test, and make any adaptation to the newer version if required
   * Submit a PR
EOF